#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/24 23:09
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : utils_email.py
# @Software: PyCharm
# @Desc    :
import yagmail
from semail.models import EmailConfig

class EmailSender:
    @staticmethod
    def get_default_config():
        """获取默认邮箱配置"""
        return EmailConfig.objects.filter(is_default=True).first()

    @staticmethod
    def send_email(to, subject, contents, attachments=None, config_id=None):
        """
        发送邮件
        :param to: 收件人（str或list）
        :param subject: 邮件主题
        :param contents: 邮件正文（支持HTML）
        :param attachments: 附件路径列表
        :param config_id: 指定配置ID（None时使用默认配置）
        """
        config = EmailConfig.objects.get(pk=config_id) if config_id else EmailSender.get_default_config()
        if not config:
            raise ValueError("未找到可用的邮箱配置")

        try:
            # 使用yagmail发送
            with yagmail.SMTP(
                user=config.email_user,
                password=config.email_password,
                host=config.email_host,
                port=config.email_port,
                smtp_ssl=config.use_ssl
            ) as yag:
                yag.send(to=to, subject=subject, contents=contents, attachments=attachments)
            return True
        except Exception as e:
            raise Exception(f"邮件发送失败: {e}")